package etc

import (
	"bufio"
	"encoding/json"
	"fmt"
	log "github.com/sirupsen/logrus"
	"os"
	"strings"
	"time"
)

//日志相关

var (
	Log  *os.File
	Logs = []string{"panic", "fatal", "error", "warn", "info", "debug", "trace", ""}
)

type LogJson struct {
	Level string    `json:"level"`
	Msg   string    `json:"msg"`
	Time  time.Time `json:"time"`
}

const (
	Panic = 0
	Fatal = 1
	Error = 2
	Warn  = 3
	Warning
	Info  = 4
	Debug = 5
	Trace = 6
	All   = 7
)

func CreatLogFile(logs *Storage) {
	path := fmt.Sprintf("%s/log", logs.LogPath)
	_ = os.Mkdir(path, os.ModePerm)
	Log, _ = os.OpenFile(fmt.Sprintf("%s/log.log", path), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)

	log.SetFormatter(&log.JSONFormatter{})

	log.SetOutput(Log)

}

func SaveLog(msg string, level uint8) {
	switch level {
	case Debug:
		log.Debug(msg)
	case Panic:
		defer func() {
			recover()
		}()
		log.Panic(msg)
	case Error:
		log.Error(msg)
	case Info:
		log.Info(msg)
	case Warn:
		log.Warn(msg)
	case Fatal:
		log.Fatal(msg)
	case Trace:
		log.Trace(msg)
	}
}

func QueryLog(logs *Storage, level uint8) (msg []string) {

	var path = fmt.Sprintf("%s/log/log.log", logs.LogPath)

	file, err := os.OpenFile(path, os.O_RDWR, 0666)
	if err != nil {
		fmt.Println("open file error", err)
	}
	defer file.Close()

	buf := bufio.NewReader(file)

	for {
		line, err := buf.ReadString('\n')
		if strings.Contains(line, Logs[level]) {
			msg = append(msg, line)
		}

		if err != nil {
			break
		}
	}

	return msg
}

func StrToJson(logs *Storage, level uint8, opT time.Time, edT time.Time) (logJson []LogJson) {
	//func StrToJson(logs *Storage, level uint8) (logJson []LogJson) {

	var (
		datAll []LogJson
		dat    LogJson
		msg    = QueryLog(logs, level)
	)

	for _, v := range msg {
		_ = json.Unmarshal([]byte(v), &dat)
		datAll = append(datAll, dat)
	}

	for _, dat := range datAll {
		if opT.Before(dat.Time) && dat.Time.Before(edT) {
			fmt.Println(dat.Time)
			fmt.Println(dat)
		}
		if dat.Time.After(edT) {
			break
		}
	}

	//for _, l := range logJson {
	//	fmt.Println(l)
	//}

	return datAll
}
